package com.shiwaixiangcun.customer.ui.dialog;

import android.app.Activity;
import android.app.DialogFragment;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.shiwaixiangcun.customer.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.tencent.qzone.QZone;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

/**
 * Author   Administrator
 * Date     2018/3/21
 * Desc     分享dialog
 *
 * @author Administrator
 */

public class ShareDialog extends DialogFragment {

    public static boolean isShow = false;
    PlatformActionListener platformActionListener;
    private RecyclerView mRecyclerView;
    private TextView mTvCancel;
    private AdapterShare mAdapterShare;
    private List<ShareEntity> mShareEntityList;
    private Activity mActivity;
    private String shareTitle;
    private String shareTitleUrl;
    private String shareText;
    private String shareImagePath;
    private String shareUrl;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isShow = true;
        mActivity = this.getActivity();
        setStyle(android.support.v4.app.DialogFragment.STYLE_NO_TITLE, R.style.UpdateAppDialog);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mActivity = null;
    }


    @Override
    public void onStart() {
        super.onStart();
        //点击window外的区域 是否消失
        getDialog().setCanceledOnTouchOutside(false);
        Window dialogWindow = getDialog().getWindow();
        dialogWindow.setGravity(Gravity.BOTTOM);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        DisplayMetrics displayMetrics = mActivity.getResources().getDisplayMetrics();
        lp.width = displayMetrics.widthPixels;
        dialogWindow.setAttributes(lp);

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        Bundle bundle = getArguments();
        if (null != bundle) {
            shareTitle = bundle.getString("title");
            shareImagePath = bundle.getString("imageUrl");
            shareText = bundle.getString("text");
            shareTitleUrl = bundle.getString("titleUrl");
            shareUrl = bundle.getString("siteUrl");
        }
        return inflater.inflate(R.layout.layout_share, container, false);

    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        initView(view);
    }

    private void initView(View view) {
        mRecyclerView = view.findViewById(R.id.rv_share);
        mTvCancel = view.findViewById(R.id.tv_share_cancel);
        mShareEntityList = new ArrayList<>();
        mAdapterShare = new AdapterShare(mShareEntityList);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mActivity);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mRecyclerView.setAdapter(mAdapterShare);
        mTvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        platformActionListener = new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                //大部分的回调方法都处于网络线程，因此可以简单默认为回调方法都不在主线程.
                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getActivity(), "分享成功！", Toast.LENGTH_SHORT).show();
                        dismiss();
                    }
                });

            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                Toast.makeText(getActivity(), "分享失败！", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel(Platform platform, int i) {
            }
        };
        mAdapterShare.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ShareEntity shareEntity = (ShareEntity) adapter.getData().get(position);
                switch (shareEntity.getId()) {
                    case 1: {
                        Wechat.ShareParams sp = new Wechat.ShareParams();
                        sp.setShareType(Platform.SHARE_WEBPAGE);
                        sp.setTitle(shareTitle);
                        sp.setText(shareText);
                        sp.setImageUrl(shareImagePath);
                        //网友点进链接后，可以看到分享的详情
                        sp.setUrl(shareUrl);
                        Platform weChat = ShareSDK.getPlatform(Wechat.NAME);
                        // 设置分享事件回调
                        weChat.setPlatformActionListener(platformActionListener);
                        // 执行分享
                        weChat.share(sp);
                        break;
                    }
                    case 2: {
                        WechatMoments.ShareParams sp = new WechatMoments.ShareParams();
                        sp.setShareType(Platform.SHARE_WEBPAGE);
                        sp.setTitle(shareTitle);
                        sp.setText(shareText);
                        sp.setImageUrl(shareImagePath);
                        //网友点进链接后，可以看到分享的详情
                        sp.setUrl(shareUrl);
                        Platform weChartMoment = ShareSDK.getPlatform(WechatMoments.NAME);
                        // 设置分享事件回调
                        weChartMoment.setPlatformActionListener(platformActionListener);
                        // 执行分享
                        weChartMoment.share(sp);
                        break;
                    }
                    case 3: {
                        QQ.ShareParams sp = new QQ.ShareParams();
                        sp.setShareType(Platform.SHARE_WEBPAGE);
                        sp.setTitle(shareTitle);
                        sp.setText(shareText);
                        sp.setImageUrl(shareImagePath);
                        //网友点进链接后，可以看到分享的详情
                        sp.setTitleUrl(shareUrl);
                        Platform qq = ShareSDK.getPlatform(QQ.NAME);
                        // 设置分享事件回调
                        qq.setPlatformActionListener(platformActionListener);
                        // 执行分享
                        qq.share(sp);
                        break;

                    }
                    case 4: {
                        QZone.ShareParams sp = new QZone.ShareParams();
                        sp.setShareType(Platform.SHARE_WEBPAGE);
                        sp.setTitle(shareTitle);
                        sp.setText(shareText);
                        sp.setTitleUrl(shareImagePath);
                        //网友点进链接后，可以看到分享的详情
                        sp.setUrl(shareUrl);
                        Platform qZone = ShareSDK.getPlatform(QZone.NAME);
                        // 设置分享事件回调
                        qZone.setPlatformActionListener(platformActionListener);
                        // 执行分享
                        qZone.share(sp);
                        break;

                    }
                    case 5: {
                        ClipboardManager cmb = (ClipboardManager) mActivity.getSystemService(Context.CLIPBOARD_SERVICE);

                        // 创建一个剪贴数据集，包含一个普通文本数据条目（需要复制的数据）
                        ClipData clipData = ClipData.newPlainText(null, shareUrl);
                        if (cmb != null) {
                            cmb.setPrimaryClip(clipData);
                            Toast.makeText(mActivity, "复制链接成功", Toast.LENGTH_SHORT).show();
                            dismiss();
                        }
                    }
                    default:
                        break;


                }
            }
        });
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();
    }

    private void initData() {
        mShareEntityList.add(new ShareEntity(1, "微信朋友", R.drawable.icon_share_wechat));
        mShareEntityList.add(new ShareEntity(2, "朋友圈", R.drawable.icon_share_moment));
        mShareEntityList.add(new ShareEntity(3, "QQ好友", R.drawable.icon_share_qq));
        mShareEntityList.add(new ShareEntity(4, "QQ空间", R.drawable.icon_share_qzone));
        mShareEntityList.add(new ShareEntity(5, "复制链接", R.drawable.icon_share_copy));
        mAdapterShare.notifyDataSetChanged();

    }

    @Override
    public void show(android.app.FragmentManager manager, String tag) {
        if (manager.isDestroyed()) {
            return;
        }

        try {
            super.show(manager, tag);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroyView() {
        isShow = false;
        super.onDestroyView();
    }

    /**
     * ShareEntity
     */
    private static class ShareEntity {
        private int id;
        private String name;
        private int cover;

        public ShareEntity(int id, String name, int cover) {
            this.id = id;
            this.name = name;
            this.cover = cover;
        }

        public int getId() {
            return id;
        }

        public String getName() {
            return name;
        }

        public int getCover() {
            return cover;
        }
    }

    /**
     * 分享适配器
     */
    private static class AdapterShare extends BaseQuickAdapter<ShareEntity, BaseViewHolder> {
        AdapterShare(@Nullable List data) {
            super(R.layout.item_share, data);
        }


        @Override
        protected void convert(BaseViewHolder helper, ShareEntity item) {
            ImageView view = helper.getView(R.id.iv_share_icon);
            helper.setText(R.id.tv_share_name, item.name);

            Glide.with(mContext).load(item.cover).into(view);

        }
    }
}
